<template>
  <div class="product-detail">
    <!-- 返回按钮 -->
    <div class="back-button" @click="router.back()">
      <van-icon name="arrow-left" size="20" />
    </div>

    <!-- 商品轮播图 -->
    <div class="product-swiper">
      <van-swipe :autoplay="3000" indicator-color="white">
        <van-swipe-item>
          <img :src="currentImage || defaultImage" class="slide-image" />
        </van-swipe-item>
      </van-swipe>
    </div>

    <!-- 商品信息 -->
    <div class="product-info">
      <div class="product-title">{{ product.name }}</div>
      <div class="product-price">{{ currentPrice }} 积分</div>
      <div class="product-stock">库存: {{ currentStock }}</div>

      <div class="product-tags">
        <van-tag type="primary" v-if="product.isNew">新品</van-tag>
        <van-tag type="danger" v-if="product.isHot">热门</van-tag>
        <van-tag type="success" v-if="currentStock > 10">库存充足</van-tag>
        <van-tag type="warning" v-else-if="currentStock > 0">库存紧张</van-tag>
        <van-tag type="danger" v-else>无库存</van-tag>
      </div>
    </div>

    <!-- 商品规格选择 -->
    <div class="product-specs" v-if="hasSpecs">
      <div class="spec-title">规格选择</div>
      <div v-for="spec in product.specs" :key="spec.id" class="spec-item">
        <div class="spec-name">{{ spec.name }}</div>
        <div class="spec-values">
          <div
            v-for="value in spec.values"
            :key="value"
            class="spec-value"
            :class="{ active: selectedSpecs[spec.name] === value, disabled: !isSpecValueAvailable(spec.name, value) }"
            @click="selectSpecValue(spec.name, value)"
          >{{ value }}</div>
        </div>
      </div>

      <!-- 调试信息 -->
      <div class="debug-info" v-if="Object.keys(selectedSpecs).length > 0">
        <div class="debug-title">已选规格:</div>
        <div
          v-for="(value, name) in selectedSpecs"
          :key="name"
          class="debug-item"
        >{{ name }}: {{ value }}</div>
        <div class="debug-title">匹配SKU:</div>
        <div
          v-if="selectedSku"
          class="debug-item"
        >ID: {{ selectedSku.id }}, 价格: {{ selectedSku.price }}, 库存: {{ selectedSku.availableStock }}</div>
        <div v-else class="debug-item">未匹配到SKU</div>
      </div>
    </div>

    <!-- 商品数量 -->
    <div class="product-quantity">
      <div class="quantity-label">购买数量</div>
      <van-stepper v-model="quantity" :min="1" :max="currentStock || 1" integer />
    </div>

    <!-- 商品详情 -->
    <div class="product-detail-info">
      <div class="detail-title">商品详情</div>
      <div class="detail-content" v-html="product.description"></div>

      <!-- 如果没有详情，显示默认文本 -->
      <div class="detail-content" v-if="!product.description">
        <p>该商品暂无详细介绍</p>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div class="action-buttons">
        <div class="action-icon" @click="router.push('/cart')">
          <van-icon name="cart-o" :badge="cartStore.totalCount || ''" size="20" />
          <span>购物车</span>
        </div>
        <div class="action-icon" @click="goToHome">
          <van-icon name="home-o" size="20" />
          <span>首页</span>
        </div>
      </div>
      <div class="buy-buttons">
        <van-button
          type="warning"
          block
          @click="addToCart"
          :disabled="currentStock <= 0 || (hasSpecs && !selectedSku)"
        >加入购物车</van-button>
        <van-button
          type="danger"
          block
          @click="buyNow"
          :disabled="currentStock <= 0 || (hasSpecs && !selectedSku)"
        >立即购买</van-button>
      </div>
    </div>

    <!-- 加载中 -->
    <div class="loading-mask" v-if="loading">
      <van-loading type="spinner" color="#1989fa" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showFailToast, showSuccessToast } from 'vant'
import { getProductDetail } from '@/api/product'
import { useCartStore } from '@/stores/cart'
import { ProductSku, CartItem } from '@/stores/types'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()

// 默认图片
const defaultImage = 'https://img01.yzcdn.cn/vant/apple-1.jpg'

// 商品信息
const product = ref<any>({})
const loading = ref(true)
const quantity = ref(1)

// 规格选择相关
const selectedSpecs = ref<Record<string, string>>({})
const selectedSku = ref<ProductSku | null>(null)

// 获取当前显示价格
const currentPrice = computed(() => {
  return selectedSku.value ? selectedSku.value.price : product.value.price
})

// 获取当前显示库存
const currentStock = computed(() => {
  if (selectedSku.value) {
    return selectedSku.value.availableStock
  }
  return product.value.availableStock || product.value.stock || 0
})

// 获取当前显示图片
const currentImage = computed(() => {
  return selectedSku.value?.image || product.value.image
})

// 是否有规格
const hasSpecs = computed(() => {
  return product.value?.specs && product.value.specs.length > 0
})

// 获取商品详情和规格
const fetchProductDetail = async () => {
  loading.value = true
  const id = route.params.id as string

  try {
    const res = await getProductDetail(Number(id))

    if (res.code === 200 && res.data) {
      product.value = res.data

      // 添加日志输出商品数据结构
      console.log(
        '商品数据:',
        JSON.stringify({
          id: product.value.id,
          name: product.value.name,
          image: product.value.image,
          coverUrl: product.value.coverUrl,
        })
      )

      if (product.value.specs && product.value.specs.length > 0) {
        console.log('商品规格数据示例:', JSON.stringify(product.value.specs[0]))
      }

      if (product.value.skus && product.value.skus.length > 0) {
        console.log('商品SKU数据示例:', JSON.stringify(product.value.skus[0]))
      }

      // 初始化商品数量
      quantity.value = 1

      // 如果有规格，初始化规格选择
      if (product.value.specs && product.value.specs.length > 0) {
        // 清空当前选择
        selectedSpecs.value = {}
      }
    } else {
      showFailToast('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    showFailToast('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 选择规格值
const selectSpecValue = (specName: string, value: string) => {
  // 检查该规格值是否可选
  if (!isSpecValueAvailable(specName, value)) {
    return
  }

  // 更新选择
  selectedSpecs.value[specName] = value

  // 尝试匹配SKU
  findMatchingSku()
}

// 检查规格值是否可选
const isSpecValueAvailable = (specName: string, value: string) => {
  // 如果没有SKU，所有规格值都可选
  if (!product.value.skus || product.value.skus.length === 0) {
    return true
  }

  // 复制当前选择
  const tempSpecs = { ...selectedSpecs.value }
  tempSpecs[specName] = value

  // 计算已选规格数量
  const selectedSpecsCount = Object.keys(tempSpecs).length

  // 如果只选了一个规格，总是可用的
  if (selectedSpecsCount <= 1) {
    return true
  }

  // 检查是否有对应的SKU
  return product.value.skus.some((sku: ProductSku) => {
    // 检查已选的规格是否匹配
    return Object.entries(tempSpecs).every(([name, val]) => {
      return sku.specs[name] === val
    })
  })
}

// 查找匹配的SKU
const findMatchingSku = () => {
  console.log(product.value.skus)
  if (!product.value.skus || product.value.skus.length === 0) {
    console.log('没有SKU数据')
    selectedSku.value = null
    return
  }

  // 获取已选规格数量
  const selectedSpecsCount = Object.keys(selectedSpecs.value).length

  console.log(
    '已选规格数量:',
    selectedSpecsCount,
    '总规格数量:',
    product.value.specs.length
  )
  console.log('已选规格:', JSON.stringify(selectedSpecs.value))

  // 如果未选择所有规格，不匹配SKU
  if (selectedSpecsCount < product.value.specs.length) {
    console.log('未选择所有规格，不进行SKU匹配')
    selectedSku.value = null
    return
  }

  console.log('尝试匹配SKU，SKU数量:', product.value.skus.length)

  // 查找匹配所有选定规格的SKU
  const matchedSkus = product.value.skus.filter((sku: ProductSku) => {
    const match = Object.entries(selectedSpecs.value).every(([name, value]) => {
      const specMatch = sku.specs[name] === value
      console.log(
        `检查SKU ID ${sku.id} 规格 "${name}": "${value}" 匹配结果:`,
        specMatch
      )
      return specMatch
    })
    return match
  })

  console.log('匹配到SKU数量:', matchedSkus.length)
  if (matchedSkus.length > 0) {
    console.log('匹配到的SKU:', JSON.stringify(matchedSkus[0]))
  }

  // 取第一个匹配的SKU
  selectedSku.value = matchedSkus.length > 0 ? matchedSkus[0] : null

  // 如果找到SKU，更新数量限制
  if (selectedSku.value) {
    if (quantity.value > selectedSku.value.availableStock) {
      quantity.value = Math.max(1, selectedSku.value.availableStock)
    }
  }
}

// 添加到购物车
const addToCart = () => {
  // 检查是否有规格需要选择
  if (hasSpecs.value && !selectedSku.value) {
    showToast('请选择商品规格')
    return
  }

  // 检查库存
  if (currentStock.value <= 0) {
    showToast('商品库存不足')
    return
  }

  // 获取商品图片地址（兼容不同字段名称）
  const productImage =
    product.value.image || product.value.coverUrl || defaultImage
  console.log('使用的商品图片:', productImage)

  let cartItem: CartItem

  if (selectedSku.value) {
    // 有SKU的情况
    cartItem = {
      id: product.value.id,
      name: product.value.name,
      price: selectedSku.value.price,
      image: selectedSku.value.image || productImage,
      stock: selectedSku.value.stock,
      availableStock: selectedSku.value.availableStock,
      skuId: selectedSku.value.id,
      skuSpecs: selectedSku.value.specs,
      quantity: quantity.value,
      checked: true,
    }
  } else {
    // 无SKU的情况
    cartItem = {
      id: product.value.id,
      name: product.value.name,
      price: product.value.price,
      image: productImage,
      stock: product.value.stock,
      availableStock: product.value.availableStock || product.value.stock,
      quantity: quantity.value,
      checked: true,
    }
  }

  cartStore.addToCart(cartItem, quantity.value)
  showSuccessToast('已添加到购物车')
}

// 立即购买
const buyNow = () => {
  // 检查是否有规格需要选择
  if (hasSpecs.value && !selectedSku.value) {
    showToast('请选择商品规格')
    return
  }

  // 检查库存
  if (currentStock.value <= 0) {
    showToast('商品库存不足')
    return
  }

  // 获取商品图片地址（兼容不同字段名称）
  const productImage =
    product.value.image || product.value.coverUrl || defaultImage
  console.log('使用的商品图片(立即购买):', productImage)

  let cartItem: CartItem

  if (selectedSku.value) {
    // 有SKU的情况
    cartItem = {
      id: product.value.id,
      name: product.value.name,
      price: selectedSku.value.price,
      image: selectedSku.value.image || productImage,
      stock: selectedSku.value.stock,
      availableStock: selectedSku.value.availableStock,
      skuId: selectedSku.value.id,
      skuSpecs: selectedSku.value.specs,
      quantity: quantity.value,
      checked: true,
    }
  } else {
    // 无SKU的情况
    cartItem = {
      id: product.value.id,
      name: product.value.name,
      price: product.value.price,
      image: productImage,
      stock: product.value.stock,
      availableStock: product.value.availableStock || product.value.stock,
      quantity: quantity.value,
      checked: true,
    }
  }

  cartStore.addToCart(cartItem, quantity.value)

  // 设置所有商品为未选中
  cartStore.cartItems.forEach(item => {
    cartStore.updateChecked(item.id, false)
  })

  // 设置当前商品为选中
  setTimeout(() => {
    const itemId = selectedSku.value
      ? `${product.value.id}_${selectedSku.value.id}`
      : product.value.id
    cartStore.updateChecked(itemId, true)

    // 跳转到订单创建页面
    router.push('/order/create')
  }, 100)
}

// 跳转到首页
const goToHome = () => {
  router.push('/home')
}

onMounted(() => {
  fetchProductDetail()
})
</script>

<style scoped lang="scss">
.product-detail {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 50px;
  position: relative;
}

.back-button {
  position: fixed;
  top: $padding-md;
  left: $padding-md;
  width: 30px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;

  .van-icon {
    color: $white;
  }
}

.product-swiper {
  height: 300px;

  .slide-image {
    width: 100%;
    height: 300px;
    object-fit: cover;
  }
}

.product-info {
  background-color: $white;
  padding: $padding-md;
  margin-bottom: $padding-xs;

  .product-title {
    font-size: 18px;
    font-weight: 500;
    color: $text-color;
    margin-bottom: $padding-sm;
  }

  .product-price {
    font-size: 20px;
    color: $danger-color;
    font-weight: 500;
    margin-bottom: $padding-xs;
  }

  .product-stock {
    font-size: $font-size-md;
    color: $text-color-light;
    margin-bottom: $padding-sm;
  }

  .product-tags {
    display: flex;
    flex-wrap: wrap;
    gap: $padding-xs;
  }
}

.product-specs {
  background-color: $white;
  padding: $padding-md;
  margin-bottom: $padding-xs;

  .spec-title {
    font-size: $font-size-md;
    color: $text-color;
    margin-bottom: $padding-sm;
  }

  .spec-item {
    margin-bottom: $padding-sm;

    .spec-name {
      font-size: $font-size-md;
      color: $text-color-light;
      margin-bottom: $padding-xs;
    }

    .spec-values {
      display: flex;
      flex-wrap: wrap;
      gap: $padding-xs;

      .spec-value {
        padding: $padding-xs $padding-sm;
        border: 1px solid #e5e5e5;
        border-radius: 4px;
        font-size: $font-size-sm;
        color: $text-color;
        cursor: pointer;

        &.active {
          color: $primary-color;
          border-color: $primary-color;
          background-color: rgba($primary-color, 0.05);
        }

        &.disabled {
          color: $text-color-light;
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }
    }
  }
}

.product-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: $white;
  padding: $padding-md;
  margin-bottom: $padding-xs;

  .quantity-label {
    font-size: $font-size-md;
    color: $text-color;
  }
}

.product-detail-info {
  background-color: $white;
  padding: $padding-md;
  margin-bottom: $padding-lg;

  .detail-title {
    font-size: $font-size-lg;
    font-weight: 500;
    color: $text-color;
    margin-bottom: $padding-md;
    border-bottom: 1px solid #f5f5f5;
    padding-bottom: $padding-xs;
  }

  .detail-content {
    font-size: $font-size-md;
    color: $text-color;
    line-height: 1.6;

    p {
      margin-bottom: $padding-md;
    }

    img {
      max-width: 100%;
      height: auto;
      margin: $padding-sm 0;
    }
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: $white;
  display: flex;
  align-items: center;
  border-top: 1px solid #f5f5f5;
  z-index: 100;

  .action-buttons {
    display: flex;
    width: 30%;
    height: 100%;

    .action-icon {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      span {
        font-size: $font-size-xs;
        color: $text-color;
        margin-top: 2px;
      }
    }
  }

  .buy-buttons {
    display: flex;
    width: 70%;
    height: 100%;

    .van-button {
      flex: 1;
      height: 100%;
      margin: 0;
      border: none;
      border-radius: 0;
    }
  }
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.spec-info {
  display: flex;
  flex-direction: column;
  margin-bottom: $padding-sm;

  .spec-title {
    font-size: $font-size-md;
    font-weight: 500;
    margin-bottom: $padding-xs;
  }

  .spec-value {
    font-size: $font-size-sm;
    color: #999;
  }
}

.debug-info {
  margin-top: $padding-md;
  padding: $padding-sm;
  background-color: #f9f9f9;
  border: 1px dashed #ddd;
  border-radius: 4px;

  .debug-title {
    font-weight: bold;
    margin-top: $padding-xs;
    margin-bottom: $padding-xs;
    color: #666;
  }

  .debug-item {
    font-size: $font-size-sm;
    color: #999;
    margin-bottom: $padding-xs;
  }
}
</style> 